#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from src.db.db_operations import DbRunner
from config.config import settings

def check_database_status():
    """检查数据库状态"""
    print("=" * 60)
    print("数据库状态检查")
    print("=" * 60)
    
    # 创建数据库连接
    dbrunner = DbRunner(
        settings.DB_HOST,
        settings.DB_USER,
        settings.DB_PASSWORD,
        settings.DB_NAME
    )
    
    try:
        # 检查test_data表
        print("\n1. 检查test_data表:")
        test_data_count = dbrunner.select_data('test_data', ['COUNT(*) as count'])
        print(f"   test_data表总记录数: {test_data_count[0]['count']}")
        
        # 检查有record_id的记录
        test_data_with_record_id = dbrunner.select_data('test_data', ['COUNT(*) as count'], 'record_id IS NOT NULL')
        print(f"   有record_id的记录数: {test_data_with_record_id[0]['count']}")
        
        # 检查test_result表
        print("\n2. 检查test_result表:")
        test_result_count = dbrunner.select_data('test_result', ['COUNT(*) as count'])
        print(f"   test_result表总记录数: {test_result_count[0]['count']}")
        
        # 检查最近的测试数据
        print("\n3. 检查最近的测试数据:")
        recent_test_data = dbrunner.select_data('test_data', ['*'], None, 5)
        print(f"   最近5条测试数据:")
        for i, data in enumerate(recent_test_data, 1):
            print(f"   {i}. ID: {data['id']}, record_id: {data.get('record_id', 'NULL')}, operation_type: {data['operation_type']}")
        
        # 检查record_id分布
        print("\n4. 检查record_id分布:")
        record_id_distribution = dbrunner.select_data('test_data', ['record_id', 'COUNT(*) as count'], 'record_id IS NOT NULL', None, 'record_id')
        print(f"   record_id分布:")
        for record in record_id_distribution:
            print(f"   record_id {record['record_id']}: {record['count']} 条记录")
        
        # 检查操作类型分布
        print("\n5. 检查操作类型分布:")
        operation_distribution = dbrunner.select_data('test_data', ['operation_type', 'COUNT(*) as count'], None, None, 'operation_type')
        print(f"   操作类型分布:")
        for op in operation_distribution:
            print(f"   {op['operation_type']}: {op['count']} 条记录")
        
        # 检查数据完整性
        print("\n6. 检查数据完整性:")
        # 检查test_data和test_result的关联
        join_query = """
        SELECT 
            td.id as test_data_id,
            td.record_id,
            td.operation_type,
            tr.id as test_result_id,
            tr.success
        FROM test_data td
        LEFT JOIN test_result tr ON td.id = tr.test_data_id
        WHERE td.record_id IS NOT NULL
        ORDER BY td.id DESC
        LIMIT 10
        """
        
        # 由于DbRunner不支持复杂查询，我们分别查询
        test_data_with_results = dbrunner.select_data('test_data', ['id', 'record_id', 'operation_type'], 'record_id IS NOT NULL', 10)
        print(f"   有record_id的测试数据 (前10条):")
        for data in test_data_with_results:
            print(f"   ID: {data['id']}, record_id: {data['record_id']}, operation_type: {data['operation_type']}")
        
        # 分析问题
        print("\n7. 问题分析:")
        if test_data_with_record_id[0]['count'] == 0:
            print("   ❌ 问题: 没有找到有record_id的测试数据")
            print("   原因: 可能是SSL证书问题导致API调用失败，没有成功创建记录")
            print("   解决方案: 需要先解决SSL证书问题，然后重新运行测试")
        else:
            print("   ✅ 找到有record_id的测试数据")
            print(f"   数量: {test_data_with_record_id[0]['count']} 条")
        
    except Exception as e:
        print(f"检查数据库状态时出错: {str(e)}")
    finally:
        dbrunner.close()

if __name__ == "__main__":
    check_database_status() 